package controllers;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.google.appengine.api.urlfetch.HTTPResponse;

import debugs.IpAddressDebug;

import models.IpAddressModel;

import entities.IpAddress;

public class IpServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String ip = URLDecoder.decode(path.toLowerCase().replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		if (ip != null && ip.isEmpty()) {
			response.sendRedirect("/msg/page-not-found");
			return;
		}
		
		IpAddressModel ipModel = IpAddressModel.getInstance();
		IpAddress ipAddress = ipModel.get(ip);
		
		if (ipAddress == null) {
			response.sendRedirect("/msg/page-not-found");
			return ;
		}
		
		/*if (ipAddress.getDecimal().isEmpty()) {
			ipAddress = getInfoIp(ipAddress);
			
		}*/
		
		//Cache header
		response.addHeader("Cache-Control", "public, max-age=60000");
		
		request.setAttribute("ipAddress", ipAddress);
		try {
			request.getRequestDispatcher("/pages/ip.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	private IpAddress getInfoIp(IpAddress ipAddress) {
		try {
			String url = "http://whatismyipaddress.com/ip/" + ipAddress.getIp();
			
			Document doc = Jsoup.connect(url).post();
				
			String decimal = doc.select("#section_content table:eq(0) tr:eq(1) td").html();
			String hostname = doc.select("#section_content table:eq(0) tr:eq(2) td").html();
			String isp = doc.select("#section_content table:eq(0) tr:eq(3) td").html();
			String organization = doc.select("#section_content table:eq(0) tr:eq(4) td").html();
			String services = doc.select("#section_content table:eq(0) tr:eq(5) td").html();
			String type = doc.select("#section_content table:eq(0) tr:eq(6) td").html();
			type = type.replaceAll("[<]{1}(a)[^>]+[>]{1}", "").replaceAll("<\\/a>", "");
			
			String assignment = doc.select("#section_content table:eq(0) tr:eq(7) td").html();
			assignment = assignment.replaceAll("[<]{1}(a)[^>]+[>]{1}", "").replaceAll("<\\/a>", "");
			
			String country = doc.select("#section_content > table tr:eq(0) td").html();
			String region = doc.select("#section_content > table tr:eq(1) td").html();
			String city = doc.select("#section_content > table tr:eq(2) td").html();
			String latitude = doc.select("#section_content > table tr:eq(3) td").html();
			String longitude = doc.select("#section_content > table tr:eq(4) td").html();
			String areaCode = doc.select("#section_content > table tr:eq(5) td").html();
			String postalCode = doc.select("#section_content > table tr:eq(6) td").html();
			
			ipAddress.setDecimal(decimal);
			ipAddress.setHostname(hostname);
			ipAddress.setIsp(isp);
			ipAddress.setOrganization(organization);
			ipAddress.setServices(services);
			ipAddress.setType(type);
			ipAddress.setAssignment(assignment);
			ipAddress.setCountry(country);
			ipAddress.setRegion(region);
			ipAddress.setCity(city);
			ipAddress.setLatitude(latitude);
			ipAddress.setLongitude(longitude);
			ipAddress.setAreaCode(areaCode);
			ipAddress.setPostalCode(postalCode);
			IpAddressDebug.debug(ipAddress);
			
			//update data
			IpAddressModel ipAddressModel = IpAddressModel.getInstance();
			ipAddressModel.insert(ipAddress);
			
			
		} catch (Exception e) {
			System.out.println("Can't get ip info for domain " + ipAddress.getIp());
		}
		
		return ipAddress;
	}
}
